<?php

namespace app\wechat\models;

use app\wechat\core\BaseModel;
use cm;
use common\models\CircuitAddress;
use Yii;
use yii\helpers\Url;

class InspectorModel extends BaseModel
{
	/*
	*登陆
	*/
	public function actionLogin(){
		$account = Cm::$req->post('account', ['null', 'empty', 'default' => '']);
		$pwd = Cm::$req->post('pwd', ['null', 'empty', 'default' => '']);
		if(empty($account)){
			Cm::$res->error("请填写账号");
		}
		if(empty($pwd)){
			Cm::$res->error("请填写密码");
		}
		$pwd = md5(md5($pwd));
		$info = Cm::$db->one("SELECT id,is_check FROM sys_manager WHERE `status`=1 AND account='{$account}' AND `password`='{$pwd}'");
		if(empty($info)){
			Cm::$res->error("账号密码不正确");	
		}else{
			if($info['is_check'] != 1){
				Cm::$res->error("该管理员不是检票员");		
			}	
			$mdata = [
				'openid' => $this->openid,
				'updatetime' => date("Y-m-d H:i:s",time())
			];
			Cm::$db->update("sys_manager",$mdata,"id={$info['id']}");
			Cm::$res->susess([],'登陆成功');
		}
	}

	/*
	*是否登录
	*/
	public function actionIslogin(){
		$info = Cm::$db->one("SELECT id FROM sys_manager WHERE openid='{$this->openid}' AND status=1 AND is_check=1");
		Cm::$res->susess(['islogin'=>empty($info)?0:1]);
	}

	/*
	*订单列表
	*/
	public function actionList(){
		$type = Cm::$req->post('type', ['null', 'empty', 'default' => 1]);
		$telkwd = Cm::$req->post('telkwd', ['null', 'empty', 'default' => '']);
		$day = Cm::$req->post('day', ['null', 'empty', 'default' => '']);
		$page = Cm::$req->post('page', ['null', 'empty', 'default' => 1]);
		$limit = Cm::$req->post('limit', ['null', 'empty', 'default' => 10]);
		$where = "";
		if(!empty($day)){
			$sday = $day." 00:00:00";
			$eday = $day." 23:59:59";
			$where .= " AND b.departuretime>='{$sday}' AND b.departuretime<='{$eday}' ";
		}
		if(!empty($telkwd)){
			if (strlen($telkwd) == 11) {
				$where .= " AND (a.user_telephone='{$telkwd}' OR a.id IN (SELECT order_id FROM order_passenger WHERE telephone='{$telkwd}')) ";
			}else{
				$where .= " AND (a.user_telephone LIKE '%{$telkwd}%' OR a.id IN (SELECT order_id FROM order_passenger WHERE telephone LIKE '%{$telkwd}%')) ";
			}
		}	
		if($type == 1){
			$where .= " AND a.is_check=0";
		}else{
			$where .= " AND a.is_check=1";
		}

//		$sql = "SELECT b.departuretime,a.id,coa.name AS citysname,cob.name AS cityename,sa.name AS sitesname,sb.name AS siteename,a.ridership,(SELECT GROUP_CONCAT(name) AS name FROM order_passenger WHERE order_id=a.id) AS passenger,a.codenum
//				FROM `order` a
//				LEFT JOIN shift b ON b.id=a.shift_id
//				LEFT JOIN circuit d  ON a.circuit_id=d.id
//				LEFT JOIN open_city coa ON coa.code=d.city_scode
//				LEFT JOIN open_city cob ON cob.code=d.city_ecode
//				LEFT JOIN site sa ON sa.id=d.site_sid
//				LEFT JOIN site sb ON sb.id=d.site_eid
//				LEFT JOIN order_car oc ON oc.order_id=a.id
//				LEFT JOIN sys_manager sm ON oc.inspector=sm.id
//				WHERE a.status=1 AND a.order_status=2 AND coa.staus=1 AND cob.stauts=1 AND sa.status=1 AND sb.staus=1 AND sm.openid='{$this->openid}' {$where} GROUP BY a.id  ORDER BY b.departuretime ASC";
        $sql = "SELECT b.departuretime,a.id,coa.name AS citysname,cob.name AS cityename,sa.name AS sitesname,sb.name AS siteename,a.ridership,(SELECT GROUP_CONCAT(name) AS name FROM order_passenger WHERE order_id=a.id) AS passenger,a.codenum
				FROM `order` a 
				LEFT JOIN shift b ON b.id=a.shift_id
				LEFT JOIN circuit d  ON a.circuit_id=d.id
				LEFT JOIN open_city coa ON coa.code=d.city_scode 
				LEFT JOIN open_city cob ON cob.code=d.city_ecode
				LEFT JOIN site sa ON sa.id=d.site_sid 
				LEFT JOIN site sb ON sb.id=d.site_eid 
				LEFT JOIN order_car oc ON oc.order_id=a.id
				LEFT JOIN sys_manager sm ON oc.inspector=sm.id 
				WHERE a.status=1 AND a.order_status=2 AND  sa.status=1  AND sm.openid='{$this->openid}' {$where} GROUP BY a.id  ORDER BY b.departuretime ASC";
		$resdata = Cm::$db->paging($sql,$page, $limit);
		if(!empty($resdata['data'])){
			foreach ($resdata['data'] as $key => &$value) {
				$departuretime = strtotime($value['departuretime']);
				$value['day'] = date("m月d日",$departuretime);
				$value['hour'] = date("H:i",$departuretime);
			}
		}	
		$resdata = empty($resdata) ? [] : $resdata;
		Cm::$res->susess($resdata);	
	}

	/*
	*订单详情
	*/
	public function actionInfo(){
		$codenum = Cm::$req->get('code', ['null', 'empty', 'default' => '']);
		if(empty($codenum)){
			$codenum = Cm::$req->post('code', ['null', 'empty', 'default' => '']);
			if(empty($codenum)){
				Cm::$res->error("错误二维码");
			}	
		}
		$id = Cm::$code->jie($codenum, true);
        if (empty($id)) {
            $id = Cm::$code->jie(urldecode($codenum), true);
            if (empty($id)){
            	$id = Cm::$code->jie(urldecode(urldecode($codenum)), true);
            	$id = empty($id) ? 0 : $id;	
            }
        }
        $id = (int)$id;
        $order = Cm::$db->one("SELECT b.departuretime,coa.name AS citysname,cob.name AS cityename,sa.name AS sitesname,sb.name AS siteename,e.plate,a.status,a.order_status,a.id
        						FROM `order` a
								LEFT JOIN shift b ON b.id=a.shift_id
								LEFT JOIN circuit d  ON a.circuit_id=d.id
								LEFT JOIN open_city coa ON coa.code=d.city_scode 
								LEFT JOIN open_city cob ON cob.code=d.city_ecode
								LEFT JOIN site sa ON sa.id=d.site_sid 
								LEFT JOIN site sb ON sb.id=d.site_eid
								LEFT JOIN order_car oc ON oc.order_id=a.id 
								LEFT JOIN car e ON e.id=oc.car_id 
        						WHERE a.id={$id} AND coa.status=1 AND cob.status=1 AND sa.status=1 AND sb.status=1 AND d.status=1 AND b.status=1");
		if(empty($order)){
			Cm::$res->error("没有获取订单信息");
		}else{
			if($order['status'] != 1){
				Cm::$res->error("该订单是无效订单");	
			}elseif ($order['order_status'] != 2) {
				Cm::$res->error("该订单不是待发车订单不能进行检票操作");	
			}
			$order['passenger'] = Cm::$db->all("SELECT id,name,telephone,seat_number,is_check FROM order_passenger WHERE order_id={$order['id']} AND status=1");
			foreach ($order['passenger'] as $key => &$value) {
				$value['telephone'] = substr_replace($value['telephone'],"****",3,4);
			}
			$departuretime = strtotime($order['departuretime']);
			$order['year'] = date("Y年m月d日",$departuretime);
			$order['day'] = date("m月d日",$departuretime);
			$order['hour'] = date("H:i",$departuretime);
			Cm::$res->susess($order);	
		}
	}

	/*
	*检票
	*/
	public function actionChecking(){
		$id = (int)Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
		$info = Cm::$db->one("SELECT a.id,a.is_check,a.order_id,oc.inspector,sm.openid FROM order_passenger a LEFT join order_car oc ON oc.order_id=a.order_id LEFT JOIN sys_manager sm ON sm.id=oc.inspector WHERE a.id={$id} AND a.status=1");
		if (empty($info)) {
			Cm::$res->error("该乘客未找到");
		}
		if($info['is_check'] == 1){
			Cm::$res->error("该乘客已检票");	
		}
		$openid = $this->openid;
		$info['openid'] = empty($info['openid']) ? '' : $info['openid'];
		if($info['openid'] != $openid) {
			$shift = Cm::$db->one("SELECT b.inspector,sm.openid FROM `order` a LEFT JOIN shift b ON b.id=a.shift_id LEFT JOIN sys_manager sm ON sm.id=b.inspector WHERE a.id={$info['order_id']} "); 
			$shift['openid'] = empty($shift['openid']) ? '' : $shift['openid'];
			if($openid != $shift['openid']){
				Cm::$res->error("对不起,您没有检票的权限");			
			}
		}
		$mdata = ['is_check'=>1,'updatetime'=>date("Y-m-d H:i:s",time())];
		Cm::$db->update("order_passenger",$mdata,"id={$id}");
		Cm::$app->log->authlog(42,$mdata,$id);
		$num = Cm::$db->one("SELECT id FROM order_passenger WHERE order_id={$info['order_id']} AND is_check=0 AND status=1");
		if(empty($num)){
			Cm::$db->update("order",['is_check'=>1,'updatetime'=>date("Y-m-d H:i:s",time())],"id={$info['order_id']}");
		}
		Cm::$res->susess([]);
	}

	/*
	*检票班次列表
	*/
	public function actionShiftlist(){
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
	    $where = "";
		$day = Cm::$req->post('day', ['null', 'empty', 'default' => '']);
		$timetype = Cm::$req->post('timetype', ['null', 'empty', 'default' => 'asc']);
		if(!empty($day)){
			$sday = $day." 00:00:00";
			$eday = $day." 23:59:59";
			$where .= " AND b.departuretime>='{$sday}' AND b.departuretime<='{$eday}' ";
		}
		$page = Cm::$req->post('page', ['null', 'empty', 'default' => 1]);
		$limit = Cm::$req->post('limit', ['null', 'empty', 'default' => 10]);
		$timetype = $timetype == 'desc' ? 'DESC' : 'ASC';
		$sql = "SELECT c.plate,oc.car_id,oc.shift_id,b.departuretime,coa.name AS citysname,cob.name AS cityename,sa.name AS sitesname,sb.name AS siteename,(SELECT count(*) as num FROM order_passenger WHERE shift_id=b.id AND car_id=oc.car_id AND status=1 AND is_check=0) as nochecknum,(SELECT count(*) as num FROM order_passenger WHERE shift_id=b.id AND car_id=oc.car_id AND status=1) as checknum FROM order_car oc
				INNER JOIN sys_manager sm on sm.id=oc.inspector
				INNER JOIN car c on c.id=oc.car_id
				INNER JOIN `order` a on a.id=oc.order_id
				LEFT JOIN shift b ON b.id=oc.shift_id
				LEFT JOIN circuit d  ON a.circuit_id=d.id
				LEFT JOIN open_city coa ON coa.code=d.city_scode 
				LEFT JOIN open_city cob ON cob.code=d.city_ecode
				LEFT JOIN site sa ON sa.id=d.site_sid 
				LEFT JOIN site sb ON sb.id=d.site_eid
				WHERE oc.status=1 AND sm.openid='{$this->openid}' AND a.status=1 AND a.order_status=2 {$where}
				GROUP BY oc.shift_id,oc.car_id
				HAVING nochecknum>0
				ORDER BY b.departuretime {$timetype}";
		$resdata = Cm::$db->paging($sql,$page, $limit);
//		echo $sql;
//		echo "<br>";
//		var_dump($resdata);
//		exit;
		if(!empty($resdata['data'])){
			foreach ($resdata['data'] as $key => &$value) {
				$departuretime = strtotime($value['departuretime']);
				$value['day'] = date("m月d日",$departuretime);
				$value['hour'] = date("H:i",$departuretime);
			}
		}	
		$resdata = empty($resdata) ? [] : $resdata;
		Cm::$res->susess($resdata);	
	}

	/*
	*检票客户列表
	*/
	public function actionPassengerlist(){
		$shift_id = Cm::$req->post('shift_id', ['null', 'empty', 'default' => 0]);
		$car_id = Cm::$req->post('car_id', ['null', 'empty', 'default' => 0]);
		if(empty($shift_id) || empty($car_id)){
			Cm::$res->error("参数错误");
		}
		$sql = "SELECT coa.name AS citysname,b.circuit_id,cob.name AS cityename,sa.name AS sitesname,sb.name AS siteename,(SELECT count(*) as num FROM order_passenger WHERE shift_id=b.id AND car_id>0 AND status=1 AND is_check=1) as nochecknum,(SELECT count(*) as num FROM order_passenger WHERE shift_id=b.id AND car_id>0 AND status=1) as checknum 
				FROM shift b 
				LEFT JOIN circuit d  ON a.circuit_id=d.id
				LEFT JOIN open_city coa ON coa.code=d.city_scode 
				LEFT JOIN open_city cob ON cob.code=d.city_ecode
				LEFT JOIN site sa ON sa.id=d.site_sid 
				LEFT JOIN site sb ON sb.id=d.site_eid
				WHERE b.shift_id={$shift_id}";
		$info = Cm::$db->one($sql);		
		$sql = "SELECT a.plate,a.c_seat,b.name,(SELECT count(*) as num FROM order_passenger WHERE shift_id=b.id AND car_id=a.id AND is_check=1 AND status=1) as checknum FROM car a LEFT JOIN car_models b on b.id=a.models_id WHERE a.id={$car_id}";
		$car = Cm::$db->one($sql);			
		$sql = "SELECT id,name,telephone,seat_number,is_check FROM order_passenger WHERE car_id={$car_id} AND shift_id={$shift_id} AND status=1 ORDER BY is_check DESC,seat_number ASC";
		$list = Cm::$db->all($sql);
        $address=CircuitAddress::find()->andWhere(['circuit_id'=>$info['circuit_id'],'is_del'=>CircuitAddress::IS_DEL_NO])
        ->sleect(['id','circuit_id','site_id','address','type'])
        ->orderBy(['type'=>SORT_ASC,'id'=>SORT_ASC])
        ->asArray()->all();
		Cm::$res->susess(['info'=>$info,'car'=>$car,'list'=>$list,'address'=>$address]);
	}
}